/*
 * @Author: xuanjiu
 * @Date: 2017-11-11 16:16:44
 * @Last Modified by: zhangxuanjiu
 * @Last Modified time: 2018-03-29 09:32:01
 */

var gulp = require('gulp');
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config.js');
var configDev = require('./webpack.config-dev.js');
var configDll = require('./webpack.config-dll.js');
const serverConfig = require('./serverConfig.js')
var del = require('del');
var path = require('path');
var imagemin = require('gulp-imagemin');
var cssmin = require('gulp-cssmin');
const gulpPngquant = require('gulp-pngquant');

// 监听html/css文件改动
gulp.task('watch', function() {
  return gulp.watch('./src/*.html', function(event) {
    gulp.src(['./src/*.html'])
      .pipe(gulp.dest('./dev/'))
  })
})

gulp.task('dev', function() {
  var compiler = webpack(configDev)
  var server = new WebpackDevServer(compiler, {
    hot: true,
    // enable HMR on the server

    contentBase: path.resolve(__dirname, 'dev'),
    // match the output path

    publicPath: '/',
    // match the output `publicPath`

    stats: { colors: true },

    proxy: {},

    port: serverConfig.port

  })
  server.listen(serverConfig.port, serverConfig.host)
})

// 清空文件夹
gulp.task('clean', function() {
  return del([
    './dist/**/*'
  ]);
});

// 复制
gulp.task('copy', ['clean'], function() {
  console.log('copy');
  gulp.src(['./src/style/*.css'])
    .pipe(gulp.dest('./dist/style/'))
  gulp.src(['./src/img/**/*'])
    .pipe(gulp.dest('./dist/img/'))
  gulp.src(['./src/*.json'])
    .pipe(gulp.dest('./dist/'))
  return gulp.src(['./src/lib/*.js'])
    .pipe(gulp.dest('./dist/lib/'))
})

gulp.task('build', ['copy'], function() {
  webpack(config).run(function() {
    console.log('build finished! start compress!')
  })
})

gulp.task('buildTest', ['copy'], function() {
  config.plugins.shift()
  config.plugins.shift()
  config.plugins.push(new webpack.DefinePlugin({
    env: JSON.stringify('dev'),
    imageStorageVersion: JSON.stringify(328),
    'process.env': {
      NODE_ENV: '"development"'
    }
  }))
  webpack(config).run(function() {
    console.log('build finished! start compress!')
  })
})

gulp.task('buildDll', function() {
  webpack(configDll).run(function() {
    console.log('build DLL finished!')
  })
})

// 清空文件夹
gulp.task('cleanLocalServer', function() {
  return del([
    './localServer/**/*'
  ]);
});

// 复制
gulp.task('deploy', ['cleanLocalServer'], function() {
  return gulp.src(['./dist/**/*'])
    .pipe(gulp.dest('./localServer'))
})
